package com.empty_pro.newone;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class RateActivity extends AppCompatActivity implements Runnable {
    private float dollarrate = 0.16f;
    private float eurorate = 0.14f;
    private float wonrate = 0.191f;
    Handler handler;

    String mYear,mMonth,mDay,year,day,month;

    private static final String TAG = "rate";

    public void save() {
        Intent intent = getIntent();
        dollarrate = intent.getFloatExtra("dollar_rate", 0.16f);
        eurorate = intent.getFloatExtra("euro_rate", 0.14f);
        wonrate = intent.getFloatExtra("won_rate", 191.0f);


        Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);

        //获取sp中保存的数据
        SharedPreferences share = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        dollarrate = share.getFloat("dollar_rate", 0.0f);
        eurorate = share.getFloat("euro_rate", 0.0f);
        wonrate = share.getFloat("won_rate", 0.0f);
        year= share.getString("year","wrong");
        day= share.getString("day","wrong");
        month= share.getString("month","wrong");
        //

        //获取年月日信息
        Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
        mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
        mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
        //

        //开启子线程
        Thread t = new Thread(this);
        if(!month.equals(mMonth)||!day.equals(mDay)||!year.equals(mYear)){
            t.start();
        }

        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 5) {
                    Bundle bundle=(Bundle) msg.obj;
                    dollarrate=bundle.getFloat("dollar-rate");
                    eurorate=bundle.getFloat("euro-rate");
                    wonrate=bundle.getFloat("won-rate");
                    //向sp中保存数据
                    SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putFloat("dollar_rate", dollarrate);
                    editor.putFloat("euro_rate", eurorate);
                    editor.putFloat("won_rate", wonrate);
                    editor.putString("year", mYear);
                    editor.putString("month", mMonth);
                    editor.putString("day", mDay);
                    editor.apply();
                    //
                    Toast.makeText(RateActivity.this,"汇率已更新",Toast.LENGTH_LONG).show();
                }
                super.handleMessage(msg);
            }
        };
    }

    public void click(View btn) {
        Log.i(TAG, "click: 1......");
        EditText input = findViewById(R.id.rmb);
        TextView txt = findViewById(R.id.txt);
        String str = input.getText().toString();
        if (str.length() == 0) {
            txt.setText("请输入RMB");
            Toast.makeText(getApplicationContext(), "请输入RMB", Toast.LENGTH_LONG).show();
            return;
        }

        float get = Float.parseFloat(str);
        float res = 0.0f;
        if (btn.getId() == R.id.dollar) {
            res = get * dollarrate;
        } else if (btn.getId() == R.id.euro) {
            res = get * eurorate;
        } else res = get * wonrate;


        String output = String.valueOf(res);
        txt.setText(output);
    }

    public void configclick(View btn) {


        Intent config = new Intent(this, ConfigActivity.class);

        config.putExtra("dollar_rate", dollarrate);
        config.putExtra("euro_rate", eurorate);
        config.putExtra("won_rate", wonrate);

        startActivity(config);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.rate_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.item1) {
            //执行
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void run() {
        Log.i(TAG, "run: run....");
        //使用Buddle传递参数
        Bundle retBuddle=new Bundle();
        //
        //获取网络资源
        //URL url = null;
        //url = new URL("www.usd-cny.com/bankofchina.htm");
        // 解析数据
        String url = "https://www.usd-cny.com/bankofchina.htm";
        try {
            Document doc = Jsoup.connect(url).get();

            Element table = doc.getElementsByTag("table").first();
            Elements tds = table.getElementsByTag("td");

            for (int i = 0; i < tds.size(); i += 6) {
                Element td1 = tds.get(i);
                Element td2 = tds.get(i + 5);
                if("美元".equals(td1.text())){
                    retBuddle.putFloat("dollar-rate",100f/Float.parseFloat(td2.text()));
                }
                if("欧元".equals(td1.text())){
                    retBuddle.putFloat(("euro-rate"),100f/Float.parseFloat(td2.text()));
                }
                if("韩元".equals(td1.text())){
                    retBuddle.putFloat(("won-rate"),100f/Float.parseFloat(td2.text()));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //将参数传回主线程
        Message msg=handler.obtainMessage(5);
        msg.obj=retBuddle;
        handler.sendMessage(msg);
        //
    }

    private String inputStream2String(InputStream inputStream) throws IOException {
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream, "gb2312");
        while (true) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
        return out.toString();
    }
}